package multiThread;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <b> 描述:</b> ;<br/>
 *
 * @author <b>作者</b>cdxuhongya@jd.com
 *         <b>时间</b>2017/3/13 15:30<br/>
 *         <b>@CopyRight (c) </b>2015-京东智能版权所有<br/>
 */

/**
 * CountDownLatch 多线程编程的一个辅助类，初始化一个值，countDown就会将该数值减一
 * 调用await方法将会阻塞，知道该数值为0
 * 与cyclicBarrier相比，与cyclicBarrier相比，与cyclicBarrier相比可以重复使用，
 * 而CountDownLatch不能进行重复使用
 * cyclicBarrier没有减数的方法，不需要调用
 *
 * */
public class CountDownLatchTest {
    private static Integer THREAD_NUM = 50;
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(THREAD_NUM);
        for (int i = 0; i < THREAD_NUM; i++) {
            executorService.submit(new MyTask(i));
        }
    }

    public static class MyTask implements Runnable{
        static final CountDownLatch countDownLatch = new CountDownLatch(THREAD_NUM);
        private Integer id;
        public MyTask(Integer id){
            this.id = id;
        }
        public void run() {
            try {
                Thread.sleep(new Random(System.currentTimeMillis()).nextInt(1000));
                System.out.println("thread--" + id + "--waiting");
                countDownLatch.countDown();
                countDownLatch.await();
                System.out.println("thread--" + id + "--running----------");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
